<template>
	<view class="labelList">
		<cu-custom bgColor="bg-gradual-blue" :isBack="true">
			<block slot="backText">返回</block>
			<block slot="content">标签管理</block>
		</cu-custom>
		<Loading :loadModal="loadModal" :hint="hint"></Loading>
		<!-- 设置列表 -->
		<view class="cu-bar bg-white solid-bottom margin-top">
			<view class='action'>
				<text class='cuIcon-titles text-orange '></text>
				标签列表
			</view>
		</view>
		<view class="padding-sm flex flex-wrap">
			<view class="padding-xs" v-for="(item,idx) in labelList" :key="idx" :data-labelname="item.value"
				:id="item._id" @tap="showLabelRelatedModal" @longpress='deleteLabelById'>
				<view class="cu-tag line-orange">{{item.value}}</view>
			</view>
		</view>
		<Nodata :noModal="noModal"></Nodata>
		<view class="box">
			<view class="cu-bar btn-group foot">
				<button class="cu-btn text-green line-green shadow" @tap='goback'>返回</button>
				<button class="cu-btn bg-green shadow-blur" @tap='showLabelModal'>新增标签</button>
			</view>
		</view>
		<!-- 新增标签窗口 -->
		<view :class="isLabelModelShow?'cu-modal show':'cu-modal'">
			<view class="cu-dialog">
				<view class="cu-bar bg-white justify-end">
					<view class='content'>新增标签</view>
					<view class='action' @tap='hideLabelModal'>
						<text class='cuIcon-close text-red'></text>
					</view>
				</view>
				<form @submit="formLabelSubmit" report-submit="true">
					<view class='padding-sm'>
						<view class="cu-form-group text-left">
							<view class='title'>标签名称:</view>
							<input placeholder="请填写名称" class='radius' name='labelName' v-model='labelName'></input>
						</view>
					</view>
					<view class="cu-bar bg-white justify-end">
						<view class='action'>
							<button class='cu-btn' @tap='hideLabelModal'>取消</button>
							<button form-type="submit" class='cu-btn margin-left bg-green'>保存</button>
						</view>
					</view>
				</form>
			</view>
		</view>
		<!-- 标签关联文章窗体 -->
		<view :class="isLabelRelatedShow?'cu-modal show':'cu-modal'" @tap="hideLabelRelatedModal">
			<view class="cu-dialog" @click.stop>
				<scroll-view scroll-x class="bg-white nav">
					<view class='flex text-center'>
						<block v-for="(item,idx) in navItems" :key="idx" :data-data="item">
							<view class="cu-item flex-sub" :class="item.index==tabCur?'text-green cur':''"
								@tap='tabSelect' :data-id="item.index">
								{{item.name}}
							</view>
						</block>
					</view>
				</scroll-view>
				<scroll-view scroll-y scroll-with-animation :scroll-top="0" style="height:calc(100vh - 475rpx)"
					@scrolltolower="bindscrolltolower">
					<checkbox-group class="block" @change="checkboxChange">
						<view class="cu-list menu text-left">
							<view class="cu-item" v-for="(item,idx) in posts" :key="idx" :id="item._id">
								<label class="flex justify-between align-center flex-sub">
									<view class="flex-sub">{{item.title}}</view>
									<checkbox :value="item._id" class="round"></checkbox>
								</label>
							</view>
						</view>
					</checkbox-group>
					<LoadMore v-if="!nodata" :status="status" mode="loading1" color="#333"></LoadMore>
					<Nodata :noModal="nodata"></Nodata>
				</scroll-view>
				<view class="cu-bar bg-white">
					<view class="action margin-0 flex-sub solid-left" @tap="hideLabelRelatedModal">
						取消
					</view>
					<view class="action margin-0 flex-sub text-green solid-left" @tap="savePostsRelatedLabel">
						{{btnName}}
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import util from '../../utils/util.js';
	import api from '../../utils/api.js';
	import Loading from '../../components/loading.vue';
	import LoadMore from "../../components/loadup.vue";
	import Nodata from '../../components/nodata.vue';
	export default {
		components: {
			Loading,
			LoadMore,
			Nodata
		},
		data() {
			return {
				imgUrl: getApp().globalData.imgUrl,
				labelList: [],
				navItems: [{
					name: '未关联',
					index: 1
				}, {
					name: '已关联',
					index: 2
				}],
				tabCur: 1,
				scrollLeft: 0,
				isLabelModelShow: false,
				isLabelRelatedShow: false,
				btnName: "保存关联",
				posts: [],
				page: 1,
				filter: {},
				checkedList: [],
				curLabelName: "",
				labelName:"",
				status: 'down',
				loadModal: false, //加载
				hint: '加载中...',
				noModal: false,
				nodata:false
			};
		},
		onLoad: async function(options) {
			await this.getLabelList();
		},
		methods: {
			/**
			 * 获取label集合
			 * @param {*} e
			 */
			async getLabelList() {
				let that = this;
				that.loadModal = true;
				that.labelList = [];
				let labelList = await api.getLabelList();
				console.info(labelList);
				that.labelList = labelList.result.data;
				that.noModal = labelList.result.data.length > 0 ? false : true;
				that.loadModal = false;
				uni.hideNavigationBarLoading();
				uni.hideLoading();
				uni.stopPullDownRefresh()
			},

			/**
			 * 返回上一页
			 * @param {*} e
			 */
			async goback(e) {
				uni.navigateBack({
					delta: 1
				})
			},
			/**
			 * tab切换
			 * @param {} e
			 */
			async tabSelect(e) {
				let that = this;
				let tabCur = e.currentTarget.dataset.id;
				let filter;
				if (tabCur === 1) {
					filter = {
						isShow: 1,
						containLabel: 2,
						label: that.curLabelName
					}
				} else {
					filter = {
						isShow: 1,
						containLabel: 1,
						label: that.curLabelName
					}
				}

				that.tabCur = tabCur;
				that.btnName = tabCur === 1 ? "保存关联" : "取消关联";
				that.scrollLeft = (tabCur - 1) * 60;
				that.page = 1;
				that.posts = [];
				that.filter = filter;
				that.checkedList = [];

				await that.getPostsList(filter);
			},

			/**
			 * 显示
			 * @param {} e
			 */
			showLabelModal(e) {
				this.isLabelModelShow = true;
			},
			/**
			 * 隐藏
			 * @param {*} e
			 */
			hideLabelModal(e) {
				this.isLabelModelShow = false;
			},
			/**
			 * 保存标签
			 * @param {*} e
			 */
			async formLabelSubmit(e) {
				let that = this;
				let labelName = e.detail.value.labelName;
				if (labelName === undefined || labelName === "") {
					uni.showToast({
						title: '请填写正确的标签',
						icon: 'none',
						duration: 1500
					})
				} else {
					that.loadModal = true; //加载
					that.hint = '保存中...';

					let res = await api.addBaseLabel(labelName);
					that.loadModal = false;
					uni.stopPullDownRefresh();
					if (res.result) {
						that.isLabelModelShow = false;
						that.hint = '加载中...';
						that.labelName = "";

						that.getLabelList();

						uni.showToast({
							title: '保存成功',
							icon: 'none',
							duration: 1500
						})
					} else {
						uni.showToast({
							title: '保存出错，请查看云函数日志',
							icon: 'none',
							duration: 1500
						})
					}
				}
			},
			async showLabelRelatedModal(e) {
				let that = this;
				let curLabelName = e.currentTarget.dataset.labelname;
				let filter = {
					isShow: 1,
					containLabel: 2,
					label: curLabelName
				}

				that.curLabelName = curLabelName;
				that.isLabelRelatedShow = true;
				that.filter = filter;
				that.hint = '加载中...';

				that.page = 1;
				that.posts = [];
				that.checkedList = [];

				await that.getPostsList(filter)
			},

			hideLabelRelatedModal(e) {
				this.isLabelRelatedShow = false;
				this.page = 1;
				this.posts = [];
				this.curLabelName = "";
				this.checkedList = [];
				this.tabCur = 1;
				this.scrollLeft = 0;
			},

			/**
			 * 删除标签
			 * @param {*} e
			 */
			async deleteLabelById(e) {
				let labelName = e.currentTarget.dataset.labelname;
				let labelId = e.currentTarget.id;
				let that = this;
				uni.showModal({
					title: '提示',
					content: '是否确认删除[' + labelName + ']标签',
					success(res) {
						if (res.confirm) {
							api.deleteConfigById(labelId).then(res => {
								that.hint = '加载中...';
								return that.getLabelList();
							}).then(res => {});
							console.log(res);
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				})
			},

			/**
			 * 获取文章列表
			 */
			async getPostsList(filter) {
				let that = this;
				let page = that.page;
				that.hint = '加载中...';
				that.loadModal = true;
				that.status ='loading';
				let result = await api.getNewPostsList(page, filter);
				that.loadModal = false;
				that.posts = that.page == 1 ? result.data : [...that.posts, ...result.data];
				that.nodata=result.data.length === 0&&page==1?true:false;
				that.status = result.data.length === 0||result.data.length<10 ? 'normal' :'down';
				if (result.data.length == 0) {
				  uni.showToast({
				    title: '没有更多数据了！',
				    icon: 'none',
				    duration: 2000
				  })
				}
				uni.hideNavigationBarLoading();
				uni.hideLoading();
				uni.stopPullDownRefresh()
			},

			/**
			 *  触发滚动底部事件
			 */
			async bindscrolltolower() {
				let that = this;
				if (that.status != 'normal') {
					that.page = that.page + 1;
					uni.showNavigationBarLoading();
					that.getPostsList(that.filter);
				} else {
					uni.showToast({
						title: '没有更多数据了！',
						icon: 'none',
						duration: 2000
					})
				};
			},

			/**
			 * checkBox变化事件
			 */
			async checkboxChange(e) {
				this.checkedList = e.detail.value;
			},
			async savePostsRelatedLabel(e) {
				let that = this;
				let posts = that.checkedList;
				if (posts.length == 0) {
					uni.showToast({
						title: '没有要保存的数据',
						icon: 'none',
						duration: 1500
					});
					return;
				}
				uni.showLoading({
					title: '处理中...',
				});
				try {
					console.info(that.curLabelName);
					let res = await api.updateBatchPostsLabel(that.curLabelName, that.tabCur == 1 ? "add" : "delete",
						posts);
					console.info(res)
					if (res.result) {
						uni.showToast({
							title: '处理成功',
							icon: 'none',
							duration: 1500
						})
						that.isLabelRelatedShow = false;
						that.posts = [];
						that.page = 1;
						that.curLabelName = "";
						that.checkedList = [];
						that.tabCur = 1;
						that.scrollLeft = 0;
					} else {
						uni.showToast({
							title: '处理失败',
							icon: 'none',
							duration: 1500
						})
					}
				} catch (e) {
					console.info(e);
					uni.showToast({
						title: '处理失败,请重试',
						icon: 'none',
						duration: 1500
					})
				}
				uni.hideLoading()
			}
		},
		/**
		 * 页面相关事件处理函数--监听用户下拉动作
		 */
		onPullDownRefresh: async function() {
			this.hint = '刷新中...';
			await this.getLabelList();
		},

		/**
		 * 页面上拉触底事件的处理函数
		 */
		onReachBottom: async function() {},
	};
</script>

<style>

</style>
